<template>
  <div>
    <!--模态窗 多行-->
    <transition
      name="custom-classes-transition"
      enter-active-class="animated fadeInDown"
      leave-active-class="animated fadeOutUp"
    >
      <div class="modal-ctrl-body" v-show="revampUser.isShow">
        <div class="modal-ctrl-main even-row-ctrl">
          <div class="modal-title">
            <p>修改用户信息</p>
          </div>
          <div class="modal-ctrl-content">

            <div class="even-row">
              <div class="modal-row">
                <div class="modal-form-key f-l indispensable">
                  用户名：
                </div>
                <input type="text" maxlength="16" placeholder="最长16个字符" v-model="userData.username" class="modal-text f-l">
              </div>

              <div class="modal-row">
                <div class="modal-form-key f-l indispensable">
                  账号：
                </div>
                <input type="text" maxlength="16" placeholder="最长16个字符" readonly="readonly" v-model="userData.loginName" class="modal-text f-l">
              </div>

              <div class="modal-row">
                <div class="modal-form-key f-l indispensable">
                  密码：
                </div>
                <input type="text"  maxlength="16" placeholder="最长16位" v-model="userData.pwd" class="modal-text f-l">
              </div>

              <div class="modal-row">
                <div class="modal-form-key f-l">
                  用户状态：
                </div>
                <select @change="selectState" :value="userData.state">
                  <option value="1">启用</option>
                  <option value="0">禁用</option>
                </select>
              </div>
              <div class="modal-row">
                <div class="modal-form-key f-l">
                  手台：
                </div>
                <input type="text" @click="broadcastingSearch('RADIO')" v-model="facilityData.RADIO.value" readonly="readonly" class="modal-text f-l">
                <input type="button" v-show="facilityData.RADIO.value" @click="clearBroadcasting('RADIO')" class="clear-select-btn" value="清除选择">
              </div>

              <div class="modal-row">
                <div class="modal-form-key f-l">
                  警务通：
                </div>
                <input type="text" @click="broadcastingSearch('appAccount')" v-model="facilityData.appAccount.value" readonly="readonly" class="modal-text f-l">
                <input type="button" v-show="facilityData.appAccount.value" @click="clearBroadcasting('appAccount')" class="clear-select-btn" value="清除选择">
              </div>

              <div class="modal-row">
                <div class="modal-form-key f-l">
                  警车：
                </div>
                <input type="text"  @click="broadcastingSearch('CAR')" v-model="facilityData.CAR.value" readonly="readonly" class="modal-text f-l">
                <input type="button" v-show="facilityData.CAR.value" @click="clearBroadcasting('CAR')" class="clear-select-btn" value="清除选择">
              </div>

              <div class="modal-row">
                <div class="modal-form-key f-l">
                  单兵：
                </div>
                <input type="text" @click="broadcastingSearch('MONITOR')" v-model="facilityData.MONITOR.value" readonly="readonly" class="modal-text f-l">
                <input type="button" v-show="facilityData.MONITOR.value" @click="clearBroadcasting('MONITOR')" class="clear-select-btn" value="清除选择">
              </div>

            </div>
          </div>
          <div class="btns text-r">
            <button type="button" class="btn btn-default" @click="close">取消</button>
            <button type="button" class="btn btn-info" @click="subUpUserData">确定</button>
          </div>
        </div>
      </div>
    </transition>

    <!--绑定设备-->
    <transition
      name="custom-classes-transition"
      enter-active-class="animated fadeInDown"
      leave-active-class="animated fadeOutUp">
      <div class="modal-ctrl-body" v-show="policeFacilityIsshow">
        <div class="modal-ctrl-main even-row-ctrl">
          <div class="modal-title">
            <p>设备选择</p>
          </div>

          <div class="modal-ctrl-content" v-show="false">
            <div class="search-ctrl f-l" >
              <form style="height: 100%;">
                <input placeholder="搜索关键字" class="search-text">
                <button class="search-btn btn btn-info" type="button">搜索</button>
              </form>
            </div>
          </div>

          <div class="table-ctrl">
            <!--表格头-->
            <div class="table-header">
              <table class="table-default">
                <thead>
                <tr>
                  <th v-for="ths in policeFacilityArr.tHeader">
                    {{ths.value}}
                  </th>
                </tr>
                </thead>
              </table>
            </div>

            <!--表格中部 -->
            <div class="table-overflowX" style="height: 300px;">
              <table class="table-default">
                <tbody>
                <tr
                  v-for="(trs,index) in policeFacilityArr.tBody"
                  @click="selectBroadcasting(trs,index)"
                  :class="{active: index === isActive}"
                >
                  <td v-for="tds in policeFacilityArr.tHeader">
                    {{trs[tds.key]}}
                  </td>
                </tr>
                </tbody>
              </table>
            </div>

          </div>

          <!--表格翻页  -->
          <Pages
            v-show="policeFacilityArr.pages !== 0"
            :showItem="5"
            :pageSize="20"
            :allDataSum="policeFacilityArr.pages"
            :allpage="(Math.ceil(policeFacilityArr.pages/20))"
            @current-change="tablePageData"
          >
          </Pages>

          <div class="btns text-r">
            <button type="button" class="btn btn-default" @click="policeFacilityIsshow = false">取消</button>
            <!--<button type="button" class="btn btn-info" >确定</button>-->
          </div>
        </div>
      </div>
    </transition>

  </div>
</template>

<script>
  import Pages from "../../sudoku/atom/pages.vue"
    export default {
        name: "RevampUserModal",
        props:["revampUser"],
        components:{
          Pages
        },
        data(){
          return{
            userData:{ //用户信息
              "loginName":"",
              "pwd":"",
              "username":"",
              "state":"0",
              "pictureUrl":"" //相片Id
            },
            isActive:-1,
            facilityData:{
              CAR:{
                value:""
              },
              RADIO:{
                value:""
              },
              appAccount:{
                value:""
              },
              MONITOR:{
                value:""
              }
            },
            policeFacilityArr:{//设备管理渲染
              tHeader:[],
              tBody:[],
              pages:0
            },
            broadcastingSelect:{
              type:"",
              value:""
            },
            photoSrc:"", //图片地址
            photoFile:"", //图片文件
            policeFacilityIsshow:false,
            userId:null,
            sessionStorage:{}
          }
        },
        watch:{
          revampUser:{
            handler(userSelect){
              if( userSelect.isShow ){
                this.initFacilityData();//设备初始化
                //部门名称和id获取
                let session = JSON.parse(sessionStorage.getItem("stationCommunication"));
                this.sessionStorage.name = session.name;
                this.sessionStorage.id = session.id;
                //console.log(userSelect);
                this.userId = userSelect.userId;

                //查询用户信息
                this.$axios.get(this.HOST+"/user/getBigUserModel",{
                  params:{
                    userId:this.userId
                  }
                })
                .then((data)=>{
                  let userModalData = data.data;
                  for( let modalKey in userModalData ){
                    for( let userDataKey in this.userData ){
                      if( userDataKey === modalKey ){
                        this.userData[userDataKey] = userModalData[userDataKey];
                      }
                    }
                  }
                  //console.log(this.userData);
                  if( this.userData.pictureUrl ){
                    this.photoSrc = baseURL+"api/jp-TIFS-FileCenter-ms/file?businessId="+this.userData.pictureUrl;
                  }else{
                    this.photoSrc = "";
                  }
                })
                .catch((err)=>{
                  //console.log(err);
                });

                //查询设备
                let params = {
                  "columns":["TARGET_ENTRY_CODE","TARGET_ID"],
                  "conditions":[
                    {
                      "field":"resource_id",
                      "symbol":"=",
                      "value":this.userId
                    }
                  ],
                  "dataTypeCode": "calendarext",
                  "pageSize": -1,
                  "tableName": "T_DA_RESOURCE_RELATION"
                };
                //console.log(params);

                //查询设备
                this.$axios.post(this.HOST+"/base/query/page",params)
                  .then((data)=>{
                    let facilityArr = data.data.data.list;
                    //已有设备渲染
                    for( let i=0;i<facilityArr.length;i++ ){
                      for( let facilityDataKey in this.facilityData ){
                        if( facilityArr[i].TARGET_ENTRY_CODE === facilityDataKey){
                          this.facilityData[facilityDataKey].value = facilityArr[i].TARGET_ID
                        }
                      }
                    }
                    //console.log(this.facilityData);
                  })
                  .catch((err)=>{
                    //console.log(err);
                  });
              }
            },
            deep:true
          }
        },
        methods:{
          //关闭弹窗
          close(){
            this.$emit("closeModalFn")
          },
          //修改用户信息
          subUpUserData(){
            //console.log(this.userData);
            let userParams = {};
            //遍历用户信息
            for( let userDataKey in this.userData ){
              userParams[userDataKey] = this.userData[userDataKey]
            }
            //console.log(this.facilityData);

           /* let facilityParams = {
              "resourceEntryCode": "POLICE",
              "resourceId": this.userId
            };*/

            //console.log(this.facilityData);
            //遍历添加设备参数
            let facilityParams = [];
            for( let key in this.facilityData ){
              ////console.log(this.facilityData[key].value);
              let params = {
                "resourceEntryCode": "POLICE",
                "resourceId": this.userId,
                "targetId":""
              };
              params.targetEntryCode = key;
              params.targetId = this.facilityData[key].value === "" ? "" : this.facilityData[key].value ;
              facilityParams.push(params);
            }
            //console.log(facilityParams);
            //console.log(userParams);

       /*     for(let i=0;i<userParams.loginName.length;i++){
              if(userParams.loginName.charCodeAt(i)>19968&&userParams.loginName.charCodeAt(i)<40869){
                alert("用户名不能为汉字！");
                return false;
              }
            }*/

            if( this.verifyForm.isNull(userParams.username) ){
              this.s_alert("用户名不能为空！");
              // alert("用户名为空！");
              return false;
            }else if( this.verifyForm.isNull(userParams.pwd) || this.verifyForm.letterAndNumber(userParams.pwd) ){
              this.s_alert("密码为空或格式不正确！只能为字母和数字！");
              // alert("密码为空！");
              return false;
            }
         /*   else if( this.verifyForm.isNull(userParams.loginName) ){
              alert("账号为空！");
              return false;
            }*/

            this.$axios["put"](this.HOST+"/user/?id="+this.userId,userParams)
              .then((data)=>{
                if( data.data.success === true ){
                  this.s_alert("修改成功！");
                  // alert("修改成功！");
                  this.s_logwrite("基础信息管理-用户管理","修改了用户信息");
                  this.$axios.post(this.HOST+"/facilityRelation/static/updateRelationship",facilityParams)
                    .then((data)=>{
                      if( data.data.success === true ){
                        this.s_alert("设备绑定成功！");
                        // alert("设备绑定成功！");
                      }
                    })
                    .catch((err)=>{
                      this.s_alert("设备绑定失败！");
                      // alert("设备绑定失败！");
                      //console.log(err);
                    });
                  if( facilityParams.length >= 1 ){

                  }
                  this.$emit("revampClose");
                }
              })
              .catch((err)=>{
                this.s_alert("修改失败！");
                // alert("修改失败！");
                //console.log(err);
              });
            //console.log(userParams);
          },
          //用户状态
          selectState(ele){
            this.userData.state = ele.target.value;
          },
          initFacilityData(){
            this.facilityData={
              CAR:{
                value:""
              },
              RADIO:{
                value:""
              },
              appAccount:{
                value:""
              },
              MONITOR:{
                value:""
              }
            }
          },
          //设备分页
          tablePageData(page){
            this.broadcastingSearch(this.broadcastingSelect.type,page);
          },
          //清除选择
          clearBroadcasting(type){
            this.facilityData[type].value = "";
          },
          //设备查询
          broadcastingSearch(type,pageIndex){
            //console.log(type);
            this.policeFacilityIsshow = true;
            this.broadcastingSelect.type = type;
            ////console.log(this.broadcastingSelect.type);
            if( type === "RADIO" ){ //手台
              this.policeFacilityArr.tHeader = [
                {"key":"IS_WORK_PARSE","value":"工作状态"},
                {"key":"NUM","value":"电台编号"},
                {"key":"STATE_PARSE","value":"在线状态"},
                {"key":"TYPE_PARSE","value":"电台类型"},
                {"key":"STATIO_ID_PARSE","value":"所属单位"},
              ];
              //设备渲染
              this.BroadcastingAjax({
                "field":"STATIO_ID",
                "tableName":"T_RES_RADIO"
              },pageIndex);
            }
            else if(type === "appAccount"){ //警务通
              this.policeFacilityArr.tHeader = [
                {"key":"IS_WORK_PARSE","value":"工作状态"},
                {"key":"NUM","value":"设备编号"},
                {"key":"STATUS_PARSE","value":"在线状态"},
              ];
              this.BroadcastingAjax({
                "field":"STATION_ID",
                "tableName":"T_RES_JWT"
              },pageIndex);
            }
            else if(type === "CAR"){ //车辆信息
              this.policeFacilityArr.tHeader = [
                {"key":"CARCODE","value":"警车车牌"},
                {"key":"CARTYPE_PARSE","value":"车辆类型"},
                {"key":"ISONLINE_PARSE","value":"是否在线"},
              ];
              this.BroadcastingAjax({
                "field":"STATIONID",
                "tableName":"T_RES_CAR_INFO"
              },pageIndex);
            }
            else if(type === "MONITOR"){ //单兵
              this.policeFacilityArr.tHeader = [
                {"key":"EQUIPNUM","value":"设备名称"},
                {"key":"TEL","value":"手机号"},
                {"key":"NAME","value":"设备名称"},
              ];
              this.BroadcastingAjax({
                "field":"STATION_ID",
                "tableName":"T_RES_DANBING"
              },pageIndex);
            }
          },
          //选择设备渲染
          BroadcastingAjax(opt,pageIndex){
            let page = "";
            if( pageIndex ){
              page = pageIndex;
            }else {
              page = "1"
            }

            let params = {
              "columns":["*"],
              "conditions":[
                {
                  "field":opt.field,
                  "symbol":"=",
                  "value":this.sessionStorage.id
                }
              ],
              "dataTypeCode":"policefacility",
              "pageIndex":page,
              "pageSize":"20",
              "tableName":opt.tableName,
            };
            //console.log(params);
            this.$axios.post(this.HOST+"/base/query/page",params)
              .then((data)=>{
                //console.log(data);
                //获取手台列表
                this.policeFacilityArr.tBody = data.data.data.list;
                this.policeFacilityArr.pages = data.data.data.total;
                ////console.log(this.policeFacilityArr.pages);
              })
              .catch((err)=>{
                //console.log(err);
              });
          },
          //设备选择
          selectBroadcasting(broadcastingObj,index){
            this.isActive = index;
            //console.log(this.broadcastingSelect.type);
            //console.log(broadcastingObj);
            for( let facilityDataKey in this.facilityData ){
               if( facilityDataKey === this.broadcastingSelect.type && this.broadcastingSelect.type === "RADIO" ){//手台
                  this.facilityData[facilityDataKey].value = broadcastingObj.NUM;
               }else if( facilityDataKey === this.broadcastingSelect.type && this.broadcastingSelect.type === "appAccount"  ){//手台
                 this.facilityData[facilityDataKey].value = broadcastingObj.NUM;
               }else if( facilityDataKey === this.broadcastingSelect.type && this.broadcastingSelect.type === "CAR"  ){//车辆信息
                 this.facilityData[facilityDataKey].value = broadcastingObj.CARCODE;
               }else if( facilityDataKey === this.broadcastingSelect.type && this.broadcastingSelect.type === "MONITOR"  ){//车辆信息
                 this.facilityData[facilityDataKey].value = broadcastingObj.EQUIPNUM;
               }
            }
            ////console.log(this.facilityData);
            this.policeFacilityIsshow = false;
            this.isActive = -1;
          },
          prohibitDot(e){
            if( e.keyCode=== 189 || e.keyCode=== 109 || e.keyCode=== 107 ||e.keyCode=== 110  ){
              this.s_alert("只能输入数字!");
              // alert("只能输入数字!");
              this.policeData.sort = " ";
            }
          },
        }
    }
</script>

<style scoped>
  .fadeInDown,.fadeOutUp{
    animation-duration: .500s;
  }

  .bounce-enter-active {
    animation: bounce-in 0.55s;
  }

  .bounce-leave-active {
    animation: bounce-in 0.55s reverse;
  }

  @keyframes bounce-in {
    0% {
      transform: scale(0);
    }
    50% {
      transform: scale(1.1);
    }
    100% {
      transform: scale(1);
    }
  }
</style>
